<template>
	<view class="apply-container">
		<view class="form-section">
			<view class="section-title">装修备案申请</view>
			
			<view class="form-item">
				<view class="item-label required">装修单元</view>
				<view class="item-content">
					<picker @change="bindUnitChange" :value="unitIndex" :range="unitList" range-key="display_name">
						<view class="uni-input" :class="{'placeholder': unitIndex === -1}">
							{{ unitIndex === -1 ? '请选择装修单元' : unitList[unitIndex].display_name }}
						</view>
					</picker>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label required">施工单位</view>
				<view class="item-content">
					<input class="uni-input" type="text" v-model="formData.construction_company" placeholder="请输入施工单位名称" />
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label required">预计工期(天)</view>
				<view class="item-content">
					<input class="uni-input" type="number" v-model="formData.estimated_duration" placeholder="请输入预计工期天数" />
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label">设计方案</view>
				<view class="item-content">
					<view class="upload-box">
						<view class="upload-list">
							<view class="upload-item" v-for="(item, index) in formData.design_plan_url" :key="index">
								<image class="upload-image" :src="item" mode="aspectFill"></image>
								<view class="upload-delete" @click.stop="removeImage(index)">×</view>
							</view>
							
							<view class="upload-add" @click="chooseImage" v-if="formData.design_plan_url.length < 5">
								<text class="upload-add-icon">+</text>
								<text class="upload-add-text">上传图片</text>
							</view>
						</view>
						<view class="upload-tips">最多上传5张图片，支持jpg、png格式</view>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label">施工人员信息</view>
				<view class="item-content">
					<view class="staff-list">
						<view class="staff-item" v-for="(staff, index) in formData.construction_staff_info" :key="index">
							<view class="staff-header">
								<view class="staff-title">施工人员 #{{ index + 1 }}</view>
								<view class="staff-delete" @click="removeStaff(index)">删除</view>
							</view>
							<view class="staff-form">
								<view class="staff-form-item">
									<view class="staff-label">姓名</view>
									<input class="staff-input" type="text" v-model="staff.name" placeholder="请输入姓名" />
								</view>
								<view class="staff-form-item">
									<view class="staff-label">电话</view>
									<input class="staff-input" type="text" v-model="staff.phone" placeholder="请输入电话" />
								</view>
								<view class="staff-form-item">
									<view class="staff-label">身份证号</view>
									<input class="staff-input" type="text" v-model="staff.id_card" placeholder="请输入身份证号" />
								</view>
							</view>
						</view>
						
						<view class="add-staff" @click="addStaff">
							<text class="add-staff-icon">+</text>
							<text class="add-staff-text">添加施工人员</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="fixed-bottom">
			<button class="submit-btn" @click="submitApplication">提交申请</button>
		</view>
	</view>
</template>

<script>
	import { createDecorationApplication, getUserAvailableUnits } from '@/api/services.js'
	import eventBus from '@/utils/eventBus.js'
	
	export default {
		data() {
			return {
				unitList: [], // 可选单元列表
				unitIndex: -1, // 选中的单元索引
				formData: {
					unit_id: '', // 单元ID
					construction_company: '', // 施工单位
					estimated_duration: '', // 预计工期
					design_plan_url: [], // 设计方案图片URL列表
					construction_staff_info: [] // 施工人员信息
				},
				submitting: false, // 是否正在提交
				fromListPage: false, // 是否从列表页进入
				loading: false // 加载状态
			}
		},
		onLoad(options) {
			// 检查是否从列表页进入
			if (options && options.from_list === 'true') {
				this.fromListPage = true
			}
			// 加载可选单元列表
			this.loadUnitList()
		},
		methods: {
			// 加载可选单元列表
			loadUnitList() {
				this.loading = true
				console.log('开始加载用户单元列表...')
				
				getUserAvailableUnits()
					.then(units => {
						console.log('获取到的用户单元列表:', JSON.stringify(units, null, 2))
						
						if (units && units.length > 0) {
							// 转换数据格式
							this.unitList = units.map(unit => ({
								unit_id: unit.unit_id,
								display_name: `${unit.building_name} ${unit.floor_label} ${unit.unit_number}`
							}))
							console.log('处理后的单元列表:', JSON.stringify(this.unitList, null, 2))
						} else {
							uni.showToast({
								title: '未找到可用单元',
								icon: 'none'
							})
							this.unitList = []
						}
					})
					.catch(error => {
						console.error('获取用户单元列表失败:', error)
						uni.showToast({
							title: '获取单元列表失败',
							icon: 'none'
						})
						this.unitList = []
					})
					.finally(() => {
						this.loading = false
					})
			},
			
			// 选择单元
			bindUnitChange(e) {
				this.unitIndex = e.detail.value
				this.formData.unit_id = this.unitList[this.unitIndex].unit_id
			},
			
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 5 - this.formData.design_plan_url.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 这里应该先上传图片到服务器，获取URL后再添加到列表
						// 暂时直接使用本地临时路径
						this.formData.design_plan_url = [...this.formData.design_plan_url, ...res.tempFilePaths]
					}
				})
			},
			
			// 移除图片
			removeImage(index) {
				this.formData.design_plan_url.splice(index, 1)
			},
			
			// 添加施工人员
			addStaff() {
				this.formData.construction_staff_info.push({
					name: '',
					phone: '',
					id_card: ''
				})
			},
			
			// 移除施工人员
			removeStaff(index) {
				this.formData.construction_staff_info.splice(index, 1)
			},
			
			// 验证表单
			validateForm() {
				if (!this.formData.unit_id) {
					uni.showToast({
						title: '请选择装修单元',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.construction_company) {
					uni.showToast({
						title: '请输入施工单位',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.estimated_duration) {
					uni.showToast({
						title: '请输入预计工期',
						icon: 'none'
					})
					return false
				}
				
				// 验证施工人员信息
				for (let i = 0; i < this.formData.construction_staff_info.length; i++) {
					const staff = this.formData.construction_staff_info[i]
					if (!staff.name || !staff.phone) {
						uni.showToast({
							title: `请完善施工人员 #${i + 1} 的信息`,
							icon: 'none'
						})
						return false
					}
				}
				
				return true
			},
			
			// 提交申请
			async submitApplication() {
				if (this.submitting) return
				
				if (!this.validateForm()) return
				
				this.submitting = true
				uni.showLoading({
					title: '提交中...'
				})
				
				try {
					const result = await createDecorationApplication(this.formData)
					console.log('提交结果:', result)
					
					uni.hideLoading()
					uni.showToast({
						title: '申请提交成功',
						icon: 'success'
					})
					
					// 触发刷新事件，通知列表页刷新
					eventBus.emit('refreshDecorationList')
					
					// 延迟导航到列表页
					setTimeout(() => {
						if (this.fromListPage) {
							// 如果是从列表页来的，直接返回上一页，列表会自动刷新
							uni.navigateBack()
						} else {
							// 如果不是从列表页来的，则替换当前页面为列表页
							uni.redirectTo({
								url: '/pages/services/decoration/list'
							})
						}
					}, 1500)
				} catch (error) {
					console.error('提交失败:', error)
					
					uni.hideLoading()
					uni.showToast({
						title: error.message || '提交失败，请重试',
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			}
		}
	}
</script>

<style lang="scss">
	.apply-container {
		padding: 20rpx;
		padding-bottom: 120rpx;
		background-color: #F8F8F8;
		min-height: 100vh;
		
		.form-section {
			background-color: #FFFFFF;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
			
			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 30rpx;
				position: relative;
				padding-left: 20rpx;
				
				&:before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 6rpx;
					height: 30rpx;
					background-color: #2979ff;
					border-radius: 3rpx;
				}
			}
			
			.form-item {
				margin-bottom: 30rpx;
				
				.item-label {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 15rpx;
					
					&.required:before {
						content: '*';
						color: #dd524d;
						margin-right: 5rpx;
					}
				}
				
				.item-content {
					.uni-input {
						height: 80rpx;
						border: 1rpx solid #eee;
						border-radius: 8rpx;
						padding: 0 20rpx;
						font-size: 28rpx;
						
						&.placeholder {
							color: #999;
						}
					}
					
					.upload-box {
						.upload-list {
							display: flex;
							flex-wrap: wrap;
							margin: 0 -10rpx;
							
							.upload-item, .upload-add {
								width: 160rpx;
								height: 160rpx;
								margin: 10rpx;
								border-radius: 8rpx;
								overflow: hidden;
							}
							
							.upload-item {
								position: relative;
								
								.upload-image {
									width: 100%;
									height: 100%;
								}
								
								.upload-delete {
									position: absolute;
									top: 0;
									right: 0;
									width: 40rpx;
									height: 40rpx;
									background-color: rgba(0,0,0,0.5);
									color: #fff;
									font-size: 30rpx;
									display: flex;
									align-items: center;
									justify-content: center;
								}
							}
							
							.upload-add {
								border: 1rpx dashed #ddd;
								display: flex;
								flex-direction: column;
								align-items: center;
								justify-content: center;
								
								.upload-add-icon {
									font-size: 50rpx;
									color: #999;
									line-height: 1;
									margin-bottom: 10rpx;
								}
								
								.upload-add-text {
									font-size: 24rpx;
									color: #999;
								}
							}
						}
						
						.upload-tips {
							font-size: 24rpx;
							color: #999;
							margin-top: 10rpx;
						}
					}
					
					.staff-list {
						.staff-item {
							background-color: #f9f9f9;
							border-radius: 8rpx;
							padding: 20rpx;
							margin-bottom: 20rpx;
							
							.staff-header {
								display: flex;
								justify-content: space-between;
								align-items: center;
								margin-bottom: 15rpx;
								
								.staff-title {
									font-size: 28rpx;
									font-weight: bold;
								}
								
								.staff-delete {
									font-size: 24rpx;
									color: #dd524d;
								}
							}
							
							.staff-form {
								.staff-form-item {
									margin-bottom: 15rpx;
									
									.staff-label {
										font-size: 26rpx;
										color: #666;
										margin-bottom: 10rpx;
									}
									
									.staff-input {
										height: 70rpx;
										border: 1rpx solid #eee;
										border-radius: 8rpx;
										padding: 0 20rpx;
										font-size: 26rpx;
										background-color: #fff;
									}
								}
							}
						}
						
						.add-staff {
							height: 80rpx;
							border: 1rpx dashed #ddd;
							border-radius: 8rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							
							.add-staff-icon {
								font-size: 30rpx;
								color: #2979ff;
								margin-right: 10rpx;
							}
							
							.add-staff-text {
								font-size: 28rpx;
								color: #2979ff;
							}
						}
					}
				}
			}
		}
		
		.fixed-bottom {
			position: fixed;
			bottom: 30rpx;
			left: 30rpx;
			right: 30rpx;
			
			.submit-btn {
				background-color: #2979ff;
				color: #fff;
				border-radius: 45rpx;
				font-size: 32rpx;
				height: 80rpx;
				line-height: 80rpx;
			}
		}
	}
</style> 